package com.one.group.user.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.mybatisflex.core.query.QueryWrapper;
import com.one.group.enums.ResultEnum;
import com.one.group.exception.BusinessException;
import com.one.group.model.entity.SpCell;
import com.one.group.model.entity.VehicleSpace;
import com.one.group.service.SpCellService;
import com.one.group.user.service.CellCacheService;
import com.one.group.user.tool.TenantTool;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class CellCacheServiceImpl implements CellCacheService {

    @Autowired
    private RedisTemplate redisTemplate;
    @DubboReference
    private SpCellService spCellService;
    @Autowired
    private TenantTool tenantTool;
    //配置缓存key的前缀
    public static final String CACHE_KEY_PREFIX = "cache:cell:";
    //配置缓存key的失效时间
    public static final Integer CACHE_KEY_EXPIRE_TIME = 60*60*7;
    @Override
    public List<SpCell> findAllCell() {
        Long tenantId =tenantTool.getTenantId();
        //1.先从redis查找数据，如果有直接返回
        List<SpCell> cellList = (List<SpCell>) redisTemplate.opsForValue().get(CACHE_KEY_PREFIX+tenantId);
        if(!ObjectUtil.isEmpty(cellList)){
            log.debug("缓存中查询到了对应的数据:{}",cellList);
            return cellList;
        }
        log.debug("缓存中没有查询到对应的数据，进行rpc的远程调用...");

        QueryWrapper query = QueryWrapper.create().from(SpCell.class);
        //2.如果缓存中没有数据，进入rpc远程调用
        List<SpCell> spCellList = spCellService.list(query);

        if(ObjectUtil.isEmpty(spCellList)){
            log.error("没有查找到对应的数据:{}",spCellList);
            throw new BusinessException(ResultEnum.NO_DATA,"没有查找到对应数据");
        }
        //3.写入数据到Redis
        redisTemplate.opsForValue().set(CACHE_KEY_PREFIX + tenantId,spCellList);

        //4.设置失效时间
        redisTemplate.expire(CACHE_KEY_PREFIX + tenantId,CACHE_KEY_EXPIRE_TIME, TimeUnit.SECONDS);

        //5.返回数据
        return spCellList;
    }

    @Override
    public void deleteCellCache(Long tenantId) {
        log.debug("删除小区缓存数据:{}",tenantId);
        redisTemplate.delete(CACHE_KEY_PREFIX+tenantId);
    }
}
